package com.enzoism.springboot.dive.util;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * Spring的ApplicationContext的持有者,可以用静态方法的方式获取spring容器中的bean
 * @Component不能去掉，否则无法调用setApplicationContext方法
 * 程序启动的时候，会自动将ApplicationContext进行注入
 */
@Component
public class SpringContextUtil implements ApplicationContextAware {
    /**
     * 上下文对象实例
     */
    private static ApplicationContext applicationContext;
 
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringContextUtil.applicationContext = applicationContext;
    }
    /**
     * 获取application上下文对象
     * @return
     */
    public static ApplicationContext getApplicationContext() {
        assertApplicationContext();
        return applicationContext;
    }
 
    /**
     * 通过name获取bean
     * @param beanName
     * @param mockDataSourceClass
     * @return
     */
    @SuppressWarnings("unchecked")
    public static <T> T getBean(String beanName, Class<T> mockDataSourceClass) {
        assertApplicationContext();
        return (T) applicationContext.getBean(beanName);
    }
 
    /**
     * 通过class获取bean
     * @param requiredType
     * @return
     */
    public static <T> T getBean(Class<T> requiredType) {
        assertApplicationContext();
        return applicationContext.getBean(requiredType);
    }
 
    private static void assertApplicationContext() {
        if (SpringContextUtil.applicationContext == null) {
            throw new RuntimeException("applicaitonContext属性为null,请检查是否注入了SpringContextHolder!");
        }
    }
}
